package net.hserver.gateway.core.strategy.imp;

import net.hserver.gateway.core.strategy.Chose;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 随机策略
 *
 * @author hxm
 */
public class RandomStrategy<T> implements Chose<T> {

    private List<T> hosts;

    private static RandomStrategy randomStrategy;

    private RandomStrategy() {
    }

    @Override
    public T choseInfo(String ip) {
        return hosts.get(ThreadLocalRandom.current().nextInt(hosts.size()));
    }

    public static <T> RandomStrategy getInstance(List<T> hosts) {
        if (randomStrategy == null) {
            synchronized (RandomStrategy.class) {
                if (randomStrategy == null) {
                    randomStrategy = new RandomStrategy();
                }
            }
        }
        randomStrategy.hosts=hosts;
        return randomStrategy;
    }
}
